package com.example.springbootjwtexample.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springbootjwtexample.utils.AgentComponent;
import com.example.springbootjwtexample.utils.HmacSHA256Util;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/home")
public class HomeController {

    @GetMapping(value = "/createJWTToken",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createJWTToken() throws Exception {
        LinkedHashMap<String,Object> headMap = new LinkedHashMap<>();
        headMap.put("v","a1");
        headMap.put("aid","app_0001");
        String nonce = RandomStringUtils.randomNumeric(16);
        headMap.put("nonce",nonce);
        headMap.put("alg","HS256");

        LinkedHashMap<String,Object> payloadMap = new LinkedHashMap<>();
        payloadMap.put("url","http://www.koal.com/");
        try {
            String base64Head = Base64.getUrlEncoder().encodeToString(JSONObject.toJSONString(headMap).getBytes(StandardCharsets.UTF_8));
            String base64Payload = Base64.getUrlEncoder().encodeToString(JSONObject.toJSONString(payloadMap).getBytes(StandardCharsets.UTF_8));
            String content = (base64Head + "." + base64Payload).replace("=","").replace("+","-").replace("/","_");;

            String requestSecret = HmacSHA256Util.hmacSHA256(AgentComponent.AGENT_KEY,content);
            String tokenContent = content.concat(".").concat(requestSecret);

            String[] chunks = tokenContent.split("\\.");
            Base64.Decoder decoder = Base64.getUrlDecoder();

            String header = new String(decoder.decode(chunks[0]));
            System.err.println("header:" + header);
            String payload = new String(decoder.decode(chunks[1]));
            System.err.println("payload:" + payload);
            return new ResponseEntity<>(tokenContent, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("false", HttpStatus.OK);
    }

    @GetMapping(value = "/createToken",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createToken(){
        LinkedHashMap<String,Object> payloadMap = new LinkedHashMap<>();
        payloadMap.put("url","http://www.koal.com");
        String token = JWTUtil.createToken(AgentComponent.getHeaderMap(),payloadMap,AgentComponent.AGENT_KEY.getBytes(StandardCharsets.UTF_8));
        return new ResponseEntity<>(token,HttpStatus.OK);
    }

    @GetMapping(value = "/parseToken",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<JWTPayload> parseToken(@RequestParam("token") final String authResponse){
        JWT jwt = JWTUtil.parseToken(authResponse);
        boolean isVerify = jwt.setKey(AgentComponent.AGENT_KEY.getBytes(StandardCharsets.UTF_8)).verify();
        System.err.println("isVerify:" + isVerify);
        JWTPayload payload = jwt.getPayload();
        System.err.println("payload:" + payload);
        JWTHeader header = jwt.getHeader();
        System.err.println("header:" + header);
        return new ResponseEntity<>(payload,HttpStatus.OK);
    }
}
